package cn.iocoder.yudao.module.engine.model.context;

import cn.iocoder.yudao.framework.common.util.object.BeanUtils;
import cn.iocoder.yudao.module.resource.api.IUserPreferenceApi;
import cn.iocoder.yudao.module.resource.api.model.userpreference.UserPreferenceSaveReqDTO;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.atomic.AtomicInteger;

@Slf4j
@Data
public class UserPreferenceContext {
    private IUserPreferenceApi userPreferenceApi;
    private final AtomicInteger changeCount = new AtomicInteger(0);
    private final Integer minWriteCount = 3;

    /**
     * 主键
     */
    private String id;

    /**
     * 三轴传感器最大变动幅度
     */
    private Integer threeAxisSensorMaxChange;

    public void setThreeAxisSensorMaxChange(Integer threeAxisSensorMaxChange) {
        this.threeAxisSensorMaxChange = threeAxisSensorMaxChange;
        changeCount.incrementAndGet();
        syn();
    }

    private void syn() {
        final int current = changeCount.get();
        if (current >= minWriteCount) {
            changeCount.set(0);

            final UserPreferenceSaveReqDTO req = BeanUtils.toBean(this, UserPreferenceSaveReqDTO.class);
            userPreferenceApi.updateUserPreferenceById(id, req);
            log.info("更新用户偏好设置, id = {}, userPreferenceCtx = {}", id, this);
        }
    }
}
